<template>
  <div class="pubComContainer">
    <van-field
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="优质评论将会被优先展示"
      show-word-limit
    ></van-field>
    <van-button class="post-btn" size="mini" :disabled="!message.length" @click="onAddComment">发布</van-button>
  </div>
</template>

<script>
import { addComment } from '@/api/comment.js'
export default {
  name: 'PubComment',
  props: {
    target: {
      type: [Number, String, Object],
      default: null
    }
  },
  inject: ['articleId'],
  data() {
    return {
      message: ''
    }
  },
  methods: {
    async onAddComment() {
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      try {
        const {
          data: { data }
        } = await addComment({
          target: this.target ? this.target : this.articleId,
          content: this.message,
          art_id: this.target ? this.articleId : null // 回复评论需传， 文章评论不需要传
        })
        if (this.target) {
            // 传过来评论id
            this.$emit('post-success-reply', data.new_obj)
        } else {
            this.$emit('post-success', data.new_obj)
        }
        this.$toast.success('发布成功')
      } catch (error) {
        this.$toast.fail('发布失败')
      }
      this.message = ''
    }
  }
}
</script>

<style scope lang="less">
.pubComContainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px 20px;
  .van-field {
    width: 100%;
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 170px;
    height: 60px;
    margin-left: 20px;
  }
}
</style>
